const duration = 2000;
const sign = require('./sign.js');


function serializeJSON(data) {
  return Object
    .keys(data)
    .map(function (keyName) {
      return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
    })
    .join('&');
}

function requestGet(requestUrl,params) {
  return new Promise((resoleve,reject) => {
    let signParams = sign.api(params);
    var token = wx.getStorageSync('token') || ""
    let headers = {};
    if (token != "") {
      headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer " + token,
      }
    } else {
      headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
      }
    }


    wx.request({
      url: requestUrl,
      data: signParams,
      header :headers,
      success: function (result) {
        if (result.data.success){
          resoleve(result.data.data)
        }else{
          wx.showToast({
            title: result.data.message,
            icon: 'none',
            mask: true,
            duration: duration
          })
        }
      },

      fail: function ({ errMsg }) {
        wx.showToast({
          title: '网络异常',
          icon: 'error',
          mask: true,
          duration: duration
        })
      }
    })
  })
}


function requestPost(requestUrl, params){
  return new Promise((resoleve, reject)=>{
    let signParams = sign.api(params);
    var token = wx.getStorageSync('token') || "";
    let headers = {};
    if (token != "") {
      headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        "Accept": "application/json",
        "Authorization": "Bearer " + token,
      }
    } else {
      headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        "Accept": "application/json"
      }
    }
  wx.request({
    url: requestUrl,
    data: signParams,
    header: headers,
    method: 'POST',
    dataType: 'json',
    responseType: 'text',
    success: function (result) {
      console.log(result);

      if (result.statusCode == 401){
        wx.showModal({
          title: '警告',
          content: '没有授权部分功能将无法正常使用',
          showCancel: true,
          cancelText: '取消',
          cancelColor: '#f00',
          confirmText: '去授权',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting();
            }
          }
        });

      }else{
        if (result.data.success) {
          resoleve(result.data.data);
        } else {
          reject(result.data.msg);
        }
      }

    
    },
    fail: function(res) {
      wx.showToast({
        title: '网络异常',
        icon: 'error',
        mask: true,
        duration: duration
      })
    },
    complete: function(res) {
      resoleve();
    },
  })
  });
}


module.exports = {
  requestGet:requestGet,
  requestPost :requestPost
}